from fdfs_client.client import get_tracker_conf, Fdfs_client

# 使用fdfs_client先下载 pip install py3Fdfs==2.2.0
"""
使用下载方式时, 会报错

fdfs_client.exceptions.ConnectionError: [-] Error: while downloading file([-] Error: while reading from socket: (timed out)).

1. 可以直接从 GitHub下载源码进行安装
https://github.com/Daphnis-z/py3fdfs-pypi.org
2. 替换 storage_client.py 代码文件
   具体路径是：[Python安装路径]/site-packages/fdfs_client/
   替换的 storage_client.py 代码(文件同级目录)
"""
class FdfsSendFile(object):

	def __init__(self):

		tracker_conf = get_tracker_conf('./client.conf')
		self.client = Fdfs_client(tracker_conf)

	def upload_file(self, filepath):
		'''文件上传'''

		#文件上传
		# result = client.upload_by_filename('Snipaste_2024-04-09_16-35-22.png')
		result = self.client.upload_by_filename(filepath)

		# print(result)
		# {'Group name': b'group1', 'Remote file_id': b'group1/M00/00/00/rBMGZWCeGhqAR_vRAAIAABZebgw.sqlite', 'Status': 'Upload successed.', 'Local file name': './db.sqlite3', 'Uploaded size': '128.00KB', 'Storage IP': b'101.133.225.166'}
		# 访问地址即可下载：http://101.133.225.166:8888/group1/M00/00/00/rBMGZWCeGhqAR_vRAAIAABZebgw.sqlite
		return result

	def download_file(self, filepath_name, serverfilename):
		'''文件下载'''
		# print(serverfilename)
		result = self.client.download_to_file(filepath_name, serverfilename)
		print(result)

		# print(result)

		return result

	def delete_file(self, serverfilename):
		'''文件删除'''
		#文件删除
		result = self.client.delete_file(serverfilename.encode())
		# print(result)
		# ('Delete file successed.', b'group1/M00/00/00/rBMGZWCeGhqAR_vRAAIAABZebgw.sqlite', b'101.133.225.166')

		return result

	def get_all_groups(self):
		'''列出所有的group信息'''
		result = self.client.list_all_groups()
		# print(result)

		return result


fds = FdfsSendFile()

"""图片上传"""
uploading = fds.upload_file(r'C:\Users\huayi\Downloads\295_413_3_12.png')
print(uploading)

# 返回示例
# {
# 	'Group name': b 'group1',
# 	'Remote file_id': b 'group1/M00/00/00/rBsAA2ZGuNOAVbKlAAMdORmwais090.jpg',
# 	'Status': 'Upload successed.',
# 	'Local file name': 'C:\\Users\\huayi\\Desktop\\小文件\\tools\\wallpaper\\static_ju\\upload\\1e9e31a53f634f1193722b0125823bf6.jpg',
# 	'Uploaded size': '199.31KB',
# 	'Storage IP': b '47.96.171.95'
# }
# 访问地址 47.96.171.95:8888/group1/M00/00/00/rBsAA2ZGuNOAVbKlAAMdORmwais090.jpg

"""文件下载"""
downloading = fds.download_file('./test.png', uploading.get('Remote file_id'))
print(downloading)


"""文件删除"""
# deleteing = fds.delete_file('group1/M00/00/00/rBsAA2ZGuNOAVbKlAAMdORmwais090.jpg')
# print(deleteing)
# 返回示例
# ('Delete file successed.', b'group1/M00/00/00/rBsAA2ZGuNOAVbKlAAMdORmwais090.jpg', b'47.96.171.95')